package com.l024.loanthief.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.l024.loanthief.constant.APPConstant;
import com.l024.loanthief.entity.ChatMessageEntity;
import com.l024.loanthief.eventbus.ChatMessageEvent;
import com.l024.loanthief.utils.ImageUtil;
import com.l024.loanthief.utils.Logutils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class ChatClient extends Service {

    private Socket client;
    private PrintStream out;//字节打印流
    private String ip;

    public ChatClient() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.ASYNC )
    public void sendMsg(ChatMessageEvent event) {
        if(event!=null){
            switch (event.getCode()){
                case APPConstant.START_CHAT_SERVICE:{
                    initSocket(event.getData()+"");
                    break;
                }
                case APPConstant.SEND_TEXT_CODE:{
                    //发送文本消息
                    ChatMessageEntity messageEntity = new ChatMessageEntity();
                    messageEntity.setType(APPConstant.SEND_TEXT_CODE);
                    messageEntity.setMsg(event.getData()+"");
                    out.println(JSON.toJSONString(messageEntity));
                    break;
                }
                case APPConstant.SEND_IMG_CODE:{
                    Observable.create(new ObservableOnSubscribe<String>(){
                        @Override
                        public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Throwable {
                            emitter.onNext(ImageUtil.imageToBase64(event.getData()+""));
                        }
                    }).subscribeOn(Schedulers.io())
                      .observeOn(Schedulers.io())
                    .subscribe(new Consumer<String>() {
                            @Override
                            public void accept(String s) throws Throwable {
                                ChatMessageEntity messageEntity = new ChatMessageEntity();
                                messageEntity.setType(APPConstant.SEND_IMG_CODE);
                                messageEntity.setMsg(s);
                                out.println(JSON.toJSONString(messageEntity));
                            }
                        });
                        break;
                    }
                case APPConstant.SEND_FILE_CODE:{
                    try {
                        File file = new File(event.getData()+"");
                        if(!file.exists()){
                            Logutils.e("文件不存在："+event.getData());
                            return;
                        }
                        FileInputStream inputStream = new FileInputStream(file);
                        byte[] buf = new byte[1024];
                        int len;
                        //写入文件名
                        out.write((file.getName()+APPConstant.START_FILE).getBytes());
                        //判断是否读到文件末尾
                        while ((len = inputStream.read(buf)) != -1) {
                            out.write(buf, 0, len);//将文件循环写入输出流 这个时候已经发送给服务端了
                        }
                        out.write(APPConstant.END_FILE.getBytes());
                        inputStream.close();
                        out.close();
                        Logutils.e("读取完毕"+client.isClosed());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    break;
                }
            }
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    private void initSocket(String ip) {
        this.ip = ip;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    client = new Socket(ip, APPConstant.PORT);
                    client.setKeepAlive(true);
                    //获取Socket的输出流，用来发送数据到服务端
                    out = new PrintStream(client.getOutputStream());
                    InputStream inputStream = client.getInputStream();
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String s = "";
                    //收到服务器发送的消息
                    while ((s = bufferedReader.readLine()) != null) {
                        Logutils.i("MainActivity:"+s);
                        //收到消息
                        if(!TextUtils.isEmpty(s)){
                            ChatMessageEntity messageEntity = JSON.parseObject(s, ChatMessageEntity.class);
                            if(messageEntity!=null){
                                switch (messageEntity.getType()){
                                    case APPConstant.CONNECT_CODE:{
                                        Logutils.i("服务器信息:"+messageEntity.getMsg());
                                        break;
                                    }
                                    case APPConstant.SEND_TEXT_CODE:{
                                        EventBus.getDefault().postSticky(new ChatMessageEvent(APPConstant.RECEIVE_TEXT_CODE,"",messageEntity.getMsg()));
                                        break;
                                    }
                                    case APPConstant.RECEIVE_IMG_CODE:{
                                        //收到图片消息
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    bufferedReader.close();
                    inputStreamReader.close();
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    Logutils.e("Socket关闭");
                    initSocket(ip);//再次连接
                }
            }
        }).start();
    }
}
